# -*- coding: utf-8 -*-
# 第一行必须有，否则报中文字符非ascii码错误
import json
import os


def save_json(_result, _file_name, _json_path=''):
    if _json_path and not os.path.exists(_json_path):
        os.makedirs(_json_path, exist_ok=True)

    if not _file_name.endswith('.json'):
        filename, _file_ext = os.path.splitext(_file_name)
        if _file_ext != '':
            raise Exception('不支持读取json以外的格式: ' + str(_file_ext))
        _real_file_name = "{0}.json".format(_file_name)
    else:
        _real_file_name = _file_name

    save_file_path = os.path.join(_json_path, _real_file_name)
    with open(save_file_path, 'w', encoding='utf8') as file_obj:
        json.dump(_result, file_obj, ensure_ascii=False, indent=2)


def load_json(_file_name, _json_path=''):
    if not _file_name.endswith('.json'):
        filename, _file_ext = os.path.splitext(_file_name)
        if _file_ext != '':
            raise Exception('不支持读取json以外的格式: ' + str(_file_ext))
        _real_file_name = "{0}.json".format(_file_name)
    else:
        _real_file_name = _file_name

    save_file_path = os.path.join(_json_path, _real_file_name)
    if not os.path.exists(save_file_path):
        raise Exception('json文件不存在: ' + str(save_file_path))

    with open(save_file_path, encoding='utf8') as file_obj:
        return json.load(file_obj)


def df_to_json(_dir, _name, _df):
    float_format = lambda x: '{:.2f}'.format(x) if isinstance(x, float) else x
    json_result = _df.applymap(float_format).to_json(orient='records', force_ascii=False, indent=4)
    # 如果你想将JSON结果保存到文件中，可以这样做：
    output_file = os.path.join(_dir, f'{_name}.json')
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(json_result)
